package com.application.Activity;

import java.util.ArrayList;

import ReadWriteXML.CMember;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.BaseExpandableListAdapter;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.ExpandableListContextMenuInfo;
import android.widget.Toast;

import com.application.Controller.ActivityController;
import com.application.Controller.NetworkController;
import com.application.Controller.ReadWriteFileController;
import com.application.DTO.RoleDTO;
import com.application.Network.NetworkLayer;
import com.application.Network.Protocol;
import com.application.PhanQuyen.Quyen;
import com.application.Tree.BoardView;
import com.application.outdoor.InvoikeServices.CayThaoLuanInvoike;
import com.application.outdoor.adapter.SubjectAdapter;
import com.application.outdoor.adapter.SubjectList;

public class od_SubjectActivity extends Activity {
	final static String TAG = Protocol.TAG;
	final private int MENU_XEM_CHI_TIET = 2;
	final private int MENU_TAO_CAY_MOI = 21;
	final private int MENU_DANH_SACH_FILE = 22;
	final private int MENU_LOG = 23;
	ExpandableListView expSubject;
	BaseExpandableListAdapter adapter;
	public static Runnable raRefreshData;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.od_activity_subject);
		ActivityController.arrActivity.add(this);
		expSubject = (ExpandableListView) findViewById(R.id.expSubject);
//		if (CommonUtilities.subjects == null) {
//			CommonUtilities.subjects = new SubjectList();
//			getSubject();
//		}
//		adapter = new SubjectAdapter(this, CommonUtilities.subjects);
//		expSubject.setAdapter(adapter);
//		registerForContextMenu(expSubject);
		raRefreshData = new Runnable() {

			@Override
			public void run() {
				adapter.notifyDataSetChanged();
			}
		};
	}
	public void fillData(){
		if (CommonUtilities.subjects == null) {
			CommonUtilities.subjects = new SubjectList();
			getSubject();
		}
		adapter = new SubjectAdapter(this, CommonUtilities.subjects);
		expSubject.setAdapter(adapter);
		registerForContextMenu(expSubject);
		raRefreshData = new Runnable() {

			@Override
			public void run() {
				adapter.notifyDataSetChanged();
			}
		};
	}
	@Override
	public void onResume(){
		super.onResume();
		fillData();
	}
	@Override
	public void onPause(){
		super.onPause();
		fillData();
	}
	
	@Override
	public void onStart(){
		super.onStart();
		fillData();
	}

	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {

		super.onCreateContextMenu(menu, v, menuInfo);
		ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo) menuInfo;

		int type = ExpandableListView.getPackedPositionType(info.packedPosition);
//		int group = ExpandableListView.getPackedPositionGroup(info.packedPosition);
//		int child = ExpandableListView.getPackedPositionChild(info.packedPosition);
		if (type == 1) {
//			menu.add(0, 1, 0, "Xem thông tin");
			menu.add(0, MENU_XEM_CHI_TIET, 0, "Xem chi tiết");
			menu.add(0,MENU_LOG,0,"Lịch sử thao tác");
		} else {
			menu.add(0, MENU_TAO_CAY_MOI, 0, "Thêm chủ đề");
			menu.add(0,MENU_DANH_SACH_FILE,0,"Danh sách tài liệu");
			
		}
	}

	public boolean onContextItemSelected(MenuItem menuItem) {
		ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) menuItem.getMenuInfo();
		int groupPos = 0, childPos = 0;
		int type = ExpandableListView.getPackedPositionType(info.packedPosition);
		if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
			groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
			childPos = ExpandableListView.getPackedPositionChild(info.packedPosition);
			final int idNhom = CommonUtilities.subjects.getGroup(groupPos).getId();
			int idCay = CommonUtilities.subjects.getMember(groupPos, childPos).getId();
			if (menuItem.getItemId() == MENU_XEM_CHI_TIET) {
				
				// gán cây hiện tại
				CommonUtilities.idCayHienTai = idCay;
				CommonUtilities.idNhomHienTai = idNhom;
				if (getCay(idCay, od_SubjectActivity.this)) {
					Intent intent = new Intent(getBaseContext(), frmTreeNodeActivity.class);
					startActivity(intent);
				}
			} else if (menuItem.getItemId() == MENU_LOG) {
				od_LogThaoTacAcivity.idCay=idCay;
				Intent iLog=new Intent(getBaseContext(), od_LogThaoTacAcivity.class);
				startActivity(iLog);
			}
		} else if (type == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
			groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
			final int idNhom = CommonUtilities.subjects.getGroup(groupPos).getId();
			if (menuItem.getItemId() == MENU_TAO_CAY_MOI) {				
				final String nguoiDung = CommonUtilities.nguoiDung.getTenDangNhap();
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				final EditText txtNoiDung = new EditText(this);
				builder.setTitle("Tạo thảo luận mới");
				builder.setView(txtNoiDung);
				builder.setNegativeButton("Hủy bỏ", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
//						Toast.makeText(getBaseContext(), "cancel", 1).show();

					}
				});
				builder.setPositiveButton("Tạo mới", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// Toast.makeText(getBaseContext(), "OK", 1).show();
						String idCay = taoCay(idNhom, nguoiDung, txtNoiDung.getText().toString()).trim();
						if (idCay == null || idCay.trim().equals("")) {
							Log.d(TAG, "Không tạo được cây mới");
						} else {
							// Gán role thành lập nhóm
							ArrayList<Quyen> ruleList = ReadWriteFileController.readRule(getApplicationContext(),
									ReadWriteFileController.RULE_BASE_PATH);
							RoleDTO roleSangLapNhom = new RoleDTO("Người sáng lập nhóm", ruleList);
							NetworkController._peer.getAccount().addRole(roleSangLapNhom);
							NetworkController._peer.getAccount().isThanhLapNhom = true;

							// gán cây hiện tại
							CommonUtilities.idCayHienTai = Integer.parseInt(idCay);						
							od_ShareFileActivity.idNhom=idNhom;
							CommonUtilities.idNhomHienTai = idNhom;
							// Start activity
							Intent i = new Intent(getBaseContext(), frmNhomChoActivity.class);
							String tenNhom = CommonUtilities.contacts.getGroupByID(idNhom).getTenNhom();
							i.putExtra(frmTaoNhom.CODE_GROUP_NAME, tenNhom);
							NetworkController.setGroupName(CommonUtilities.contacts.getGroupByID(idNhom).getTenNhom());
							NetworkLayer.amountMemberGroup=CommonUtilities.contacts.getNguoiTrongNhom(idNhom).size();
							createMemberFile();
							startActivity(i);
						}
					}
				});
				builder.create().show();
			}else if (menuItem.getItemId()==MENU_DANH_SACH_FILE){
				od_ShareFileActivity.idNhom=idNhom;
				Intent iShareFile=new Intent(od_SubjectActivity.this,od_ShareFileActivity.class);
				startActivity(iShareFile);
			}

		}

		return super.onContextItemSelected(menuItem);

	}

	public static boolean getCay(int idCay, Context context) {
		try {
			String rs = new CayThaoLuanInvoike().getCay(idCay);
			if (!rs.trim().equals(Protocol.SERVER_ERROR)) {
				ReadWriteFileController.writeFile(BoardView.treePath, rs);
				return true;
			}
		} catch (Exception e) {
			Toast.makeText(context, "Không thể lấy cây id=" + idCay, Toast.LENGTH_SHORT).show();
			Log.d("Phu", "Không thể lấy cây id=" + idCay);
			return false;
		}
		return false;
	}

	private String taoCay(int idNhom, String nguoiTao, String noiDung) {
		String rs = "";
		try {
			rs = new CayThaoLuanInvoike().taoCayMoi(idNhom, nguoiTao, noiDung);
			Log.d("Phu", "Tao cay=" + rs);
		} catch (Exception e) {
			Log.d("Phu", "Ko tao cay đc");
			e.printStackTrace();
			rs = "";
		}
		return rs;
	}

	private void getSubject() {
		try {
			String nguoiDug = CommonUtilities.nguoiDung.getTenDangNhap();
			String data = new CayThaoLuanInvoike().getSubject(nguoiDug);			
			CommonUtilities.subjects.init(data);			
		} catch (Exception e) {
			Log.d("Phu", "Không thể get đc subjects");
		}
	}

	public static void createMemberFile() {
		CMember member = new CMember();
		member.set_fullName(CommonUtilities.nguoiDung.getTenDangNhap());
		member.set_ip(CommonUtilities.nguoiDung.getTenDangNhap());
		member.set_userName(CommonUtilities.nguoiDung.getTenDangNhap());
		ReadWriteFileController.deleteFile(ReadWriteFileController.MEMBER_PATH);
		ReadWriteFileController.insertMember(ReadWriteFileController.MEMBER_PATH, member);
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		Log.d("PEERDROID", " vao on key down");
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setIcon(R.drawable.img_dialog);
			builder.setMessage("Thoát khỏi chương trình ?").setCancelable(false)
					.setPositiveButton("Có", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int id) {
							if(NetworkController._peer.getAccount().isThanhLapNhom){
								NetworkController._peer.getAccount().isThanhLapNhom=false;
							}
							finish();
							
						}
					}).setNegativeButton("Không", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
						}
					});
			AlertDialog alert = builder.create();
			alert.getWindow().setBackgroundDrawable(new ColorDrawable(Color.argb(0, 255, 255, 255)));
			alert.show();
			
		}
		return super.onKeyDown(keyCode, event);
	}
}
